﻿using Syspetro.Aliyun;
using Syspetro.Core.AppDeal;
using Syspetro.Core.CommandBus;
using Syspetro.Core.Extensions;
using Syspetro.Core.Resources;
using Syspetro.Core.SysInterface;
using Syspetro.Deploy.Managers;
using Syspetro.DepRedis;
using System;

namespace BJ.AuthDomain.Commands
{
    /// <summary>
    /// 发送Email(不需要登录)
    /// </summary>
    public class SendEmailCommand : Command
    {
        public string Email { get; set; }
    }
    public interface ISendEmailCommandHandler : ICommandHandler<SendEmailCommand>, ITransientService
    {

    }
    public class SendEmailCommandHandler : CommandHandler<SendEmailCommand>, ISendEmailCommandHandler
    {
        readonly IAuthorizationManager _authorization;
        readonly IEmailService _emailService;
        public SendEmailCommandHandler(IAuthorizationManager authorization, IEmailService emailService)
        {
            _emailService = emailService;
            _authorization = authorization;
        }
        public override SpActionResult<string> Execute(SendEmailCommand command)
        {
            var code = RandomGenerater.Captcha();
            var content = string.Format(SharedResource.TempleteEmail, code, _emailService.GetValidTime());
            var (status, msg) = _emailService.Notify(command.Email, content);
            if (status)
            {
                var ip = _authorization.IP;
                RedisHelper redis = new("EmailCode");
                redis.StringSet(ip + command.Email, code, new TimeSpan(0, _emailService.GetValidTime(), 0));
                return new SpActionResult<string> { Success = status, Msg = SharedResource.SendOk };
            }
            else
            {
                return new SpActionResult<string> { Success = status, Msg = msg };
            }
        }
    }
}
